package com.lixin.web.webSocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: 缓存函数 建立事件与函数的映射
 * Copyright:   Copyright (c)2023
 * Company:     sci
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2023-07-25 00:05:43
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2023-07-25     张李鑫                     1.0         1.0 Version
 */
@Component
public class WebSocketMethodMapper {
    private final Map<String, Map<String, Method>> methodMap;
    private final Map<String, WebSocketManager> webSocketManagerMap;


    @Autowired
    public WebSocketMethodMapper(Map<String, WebSocketManager> webSocketManagerMap) {
        this.webSocketManagerMap = webSocketManagerMap;
        methodMap = createMethodMap(webSocketManagerMap);
    }

    private Map<String, Map<String, Method>> createMethodMap(Map<String, WebSocketManager> webSocketManagerMap) {
        Map<String, Map<String, Method>> methodMap = new HashMap<>();
        webSocketManagerMap.forEach((k, v) -> methodMap.put(k, extractMethods(v)));
        return methodMap;
    }

    private Map<String, Method> extractMethods(WebSocketManager manager) {
        Map<String, Method> map = new HashMap<>();
        Method[] methods = manager.getClass().getMethods();
        for (Method method : methods) {
            map.put(method.getName(), method);
        }
        return map;
    }


    public Map<String, Map<String, Method>> getMethodMap() {
        return methodMap;
    }

    public Map<String, WebSocketManager> getBean() {
        return webSocketManagerMap;
    }

    public boolean hasFunc(String pre, String func) {
        return hasModel(pre) && methodMap.get(pre).containsKey(func);
    }

    public boolean hasModel(String pre) {
        return webSocketManagerMap.containsKey(pre);
    }
}
